package com.pisolution.scheduler.runtime.registry;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.io.Closeable;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 借助zookeeper实现的节点注册中心.
 *
 * @author sora
 * @version 0.1.0
 */
@Service
public class RegistryCenter implements InitializingBean, Closeable {
    /** 带有缓存措施的数据中心交互客户端. */
    private final CachedZookeeperClient client;

    // -------------------------------------------------------------------------------------------------

    /** 用于确认注册中心是否已经启动. */
    private final AtomicBoolean isStarted = new AtomicBoolean(false);

    // -------------------------------------------------------------------------------------------------
    //  初始化
    // -------------------------------------------------------------------------------------------------

    public RegistryCenter(@Qualifier("cachedZookeeperClient") final CachedZookeeperClient client) {
        this.client = client;
    }

    // -------------------------------------------------------------------------------------------------
    //  属性访问
    // -------------------------------------------------------------------------------------------------

    public CachedZookeeperClient getClient() {
        return this.client;
    }

    // -------------------------------------------------------------------------------------------------
    //  生命周期
    // -------------------------------------------------------------------------------------------------

    @Override
    public void afterPropertiesSet() {
        if (this.isStarted.compareAndSet(false, true)) {
            this.client.persist("/servers/master", "");
            this.client.persist("/servers/worker", "");
        }
    }

    @Override
    public void close() {
        if (this.isStarted.compareAndSet(true, false)) {
            if (this.client != null) {
                this.client.close();
            }
        }
    }

    // -------------------------------------------------------------------------------------------------
    //  节点查询
    // -------------------------------------------------------------------------------------------------

    /**
     * 查询注册中心中持有的管理节点.
     *
     * @return 所有注册到注册中心的管理节点网络地址信息.
     */
    public Set<String> getMasterServers() {
        return new HashSet<>(this.client.children("/servers/master"));
    }
}
